package com.zsw.talk;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServerHandler extends SimpleChannelInboundHandler<String>{
	
	private final static Logger LOG = LoggerFactory.getLogger(ServerHandler.class);
	
	@Override
	public void channelRead0(ChannelHandlerContext ctx, String body) throws Exception {
        if(getList().size() > 1){
        	int ii = getList().indexOf(ctx);
        	ChannelHandlerContext other = getList().get(ii == 0 ? 1 : 0);
        	LOG.info("给另一个客户端发送消息:{}", body);
        	other.writeAndFlush(body);
        }else{
        	LOG.info("Client :" + body);
        	ctx.writeAndFlush("无其他用户在线");
        }
   	}
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    	getList().add(ctx);
    	LOG.info("信息：有一客户端链接到本服务端,当前客户端数量：{}", getList().size());
    	ctx.writeAndFlush("你与服务器建立一个连接。");
    	new Thread(() -> {
    		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            for (;;) {
                String line = null;
				try {
					line = in.readLine();
				} catch (Exception e) {
					e.printStackTrace();
				}
                if (line == null || "quit".equalsIgnoreCase(line)) {
                    break;
                }
                byte[] req = line.getBytes();
                ctx.writeAndFlush(Unpooled.buffer(req.length).writeBytes(req));
            }
    	}).start();
    }
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    	super.channelInactive(ctx);
    	getList().remove(ctx);
    	LOG.info("有一客户端断开本服务端,剩余客户端数量：{}", getList().size());
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.disconnect();
        ctx.close();
        getList().remove(ctx);
    }
    private List<ChannelHandlerContext> getList(){
    	return Server.list;
    }
}
